﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Security.Cryptography;
namespace LCL
{
    /// <summary>
    /// 系统相关函数
    /// </summary>
    public class SystemUtility
    {
        /// <summary>
        /// 判断系统是32位还是64位
        /// </summary>
        /// <returns></returns>
        public static string Detect3264()
        {
            ConnectionOptions oConn = new ConnectionOptions();
            System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);
            System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();
            string addressWidth = null;
            foreach (ManagementObject oReturn in oReturnCollection)
            {
                addressWidth = oReturn["AddressWidth"].ToString();
            }
            return addressWidth;
        }

        /// <summary>
        /// 获取本计算机唯一的机器码
        /// </summary>
        /// <returns>字符串形式的机器码</returns>
        public static string GetInfo()
        {
            string unique = "";
            // 获取处理器信息
            ManagementClass cimobject = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = cimobject.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                unique += mo.Properties["ProcessorId"].Value.ToString();
            }
            // 获取硬盘ID  
            ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moc1 = cimobject1.GetInstances();
            foreach (ManagementObject mo in moc1)
            {
                unique += (string)mo.Properties["Model"].Value;
                break;
            }
            // 获取BIOS
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("Select SerialNumber From Win32_BIOS");
            ManagementObjectCollection moc2 = searcher.Get();
            if (moc2.Count > 0)
            {
                foreach (ManagementObject share in moc2)
                {
                    unique += share["SerialNumber"].ToString();
                }
            }
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            return Utils.ByteToHexString(md5.ComputeHash(Encoding.Unicode.GetBytes(unique))).Substring(0, 25);
        }
    }
}
